<?php

declare(strict_types=1);
// +----------------------------------------------------------------------
// | swiftAdmin 极速开发框架 [基于WebMan开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2030 http://www.swiftadmin.net
// +----------------------------------------------------------------------
// | swiftAdmin.net High Speed Development Framework
// +----------------------------------------------------------------------
// | Author: meystack <coolsec@foxmail.com> Apache 2.0 License
// +----------------------------------------------------------------------
namespace app\admin\controller\system;


use app\AdminController;
use app\common\library\Ip2Region;
use app\common\model\system\Formula as Formulas;
use app\common\model\system\Material;
use support\Response;
use system\Random;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use Webman\Http\Request;

/**
 * 用户管理
 * Class User
 * @package app\admin\controller\system
 */
class Formula extends AdminController
{
    // 初始化函数
    public function __construct()
    {
        parent::__construct();
        $this->model = new Formulas();
    }

    /**
     * 获取资源
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index(): \support\Response
    {
        if (request()->isAjax()) {
            // 查询参数
            $where = array();
            $post['title'] = input('title');
            $post['material'] = input('material');
            if (!empty($post['title'])) {
                $where[] = ['title', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['material'])) {
                $post['material'] = json_encode($post['material']); 
                $where[] = ['list', 'like', '%' . $post['material'] . '%'];
            }
            // 获取总数
            $total = $this->model->count();
            $list = $this->model->where($where)->select()->toArray();
            foreach ($list as $key => $value) {
                $list[$key]['title'] = __($value['title']);
                $tl = json_decode($value['list'] ?? '', true) ?? [];
                $text = '';
                $total = 0;
                foreach ($tl as $tv) {
                    $text .= '【' . ($tv['matitle'] ?? '') .$tv['size']. '】';
                    $total += (float)($tv['size'] ?? 0);
                }
                $list[$key]['text'] = $text;
                if($total > 0){
                    $list[$key]['total'] = $total;
                }else{
                    $list[$key]['total'] = '';
                }
            }
            // 自定义查询
            if (count($list) < $total) {
                $parentNode = []; // 查找父节点
                foreach ($list as $key => $value) {
                    if ($value['topid'] !== 0 && !list_search($list, ['id' => $value['topid']])) {
                        $parentNode[] = $this->parentNode($value['topid']);
                    }
                }
                foreach ($parentNode as $key => $value) {
                    $list = array_merge($list, $value);
                }
            }
            return $this->success(
                '获取成功',
                '',
                [
                    'item' => $list
                ],
                count($list),
                0
            );
        }
        $material = (new Material())->select();
        return view('/system/formula/index', ['material' => $material]);
    }

    /**
     * 递归查询父节点
     * @access public
     * @param int $pid 查询条件
     * @param array $array 返回数组
     * @return array
     */
    public function parentNode(int $pid, array &$array = []): array
    {
        $result = $this->model->where('id', $pid)->find()->toArray();
        if (!empty($result)) {
            /**
             * 多语言字段
             */
            if (isset($result['title'])) {
                $result['title'] = __($result['title']);
            }

            $array[] = $result;
            if ($result['topid'] !== 0) {
                $this->parentNode($result['topid'], $array);
            }
        }

        return $array;
    }

    /**
     * 添加栏目
     */
    public function add()
    {
        if (request()->isPost()) {
            $post = request()->post();
            $post = request_validate_rules($post, get_class($this->model));
            if (empty($post) || !is_array($post)) {
                return $this->error($post);
            }
            if ($this->model->create($post)) {
                return $this->success('添加成功！');
            }
            return $this->error('添加失败！');
        }
    }

    /**
     * 添加配方
     */
    public function fadd()
    {
        $id = input('id');
        if (request()->isPost()) {
            $post = request()->post();
            $post = request_validate_rules($post, get_class($this->model));
            if (empty($post) || !is_array($post)) {
                return $this->error($post);
            }
            $post['topid'] = $post['topid'] ?? 0;
            $post['list'] = $post['list'] ?? [];
            if (!is_array($post['list'])) {
                return $this->error('数据添加错误');
            }
            foreach ($post['list'] as $k => $list) {
                if (empty($list['material'])) {
                    return $this->error('数据不能为空或0');
                }
                $material = (new Material())->where('id', $list['material'])->find();
                if (empty($material)) {
                    return $this->error('第' . ($k + 1) . '行原材料被移出，请重新添加或删除此行');
                }
                $post['list'][$k]['matitle'] = $material['title'] ?? '';
                $post['list'][$k]['size'] = (float)$list['size'] ?? 0;
            }
            $post['list'] = json_encode($post['list']);
            if (!empty($post['id'])) {
                if ($post['id'] == $post['topid']) {
                    return $this->error('上级栏目不可为自己');
                }
                $res = $this->model->update($post);
            } else {
                $res = $this->model->create($post);
            }
            if ($res) {
                return $this->success('添加成功！');
            }
            return $this->error('添加失败！');
        }
        if (request()->isAjax()) {
            $id = input('id');
            $data = $this->model->find($id);
            if ($data) {
                $lists = json_decode($data['list'] ?? '', true) ?? [];
                foreach ($lists as &$list) {
                    $list['size'] = (float)$list['size'];
                }
                $data['list'] = $lists;
            }
            return $this->success('获取成功', '', $data);
        }
        //顶级栏目
        //原材料
        $material = (new Material())->field('id,title')->select();
        $data = $this->model->find($id);
        if ($data) {
            $tops = $this->model->field('id,title')->where('id', '<>', $id)->where('topid', 0)->select();
            $data['list'] = json_decode($data['list'] ?? '', true) ?? [];
        } else {
            $tops = $this->model->field('id,title')->where('topid', 0)->select();
            $data = $this->getTableFields();
        }
        return view('/system/formula/fadd', [
            'data' => $data,
            'tops' => $tops,
            'material' => $material
        ]);
    }


    /**
     * 删除轮播图
     */
    public function del()
    {
        $id = input('id');
        if (!empty($id) && is_numeric($id)) {
            if ($this->model::destroy($id)) {
                return $this->success('删除成功！');
            }
        }
        return $this->error('删除失败，请检查您的参数！');
    }
}
